package com.macro.mall.portal.sms.config;

import com.macro.mall.common.enums.SourceTypeEnum;
import com.macro.mall.portal.service.SmsMessageHistoryService;
import com.macro.mall.portal.sms.SmsLocalMessage;
import com.macro.mall.portal.sms.SmsMessageService;
import com.macro.mall.portal.sms.SmsTencentMessage;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 郎
 */
@Configuration
@EnableConfigurationProperties(MessageProperties.class)
@AllArgsConstructor
public class MessageAutoConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(MessageAutoConfiguration.class);
    private final MessageProperties properties;
    private final SmsMessageHistoryService smsMessageHistoryService;

    @Bean
    public SmsMessageService smsMessageService() {
        SmsMessageService smsMessageService = new SmsMessageService();
        String active = this.properties.getActive();
        logger.info("当前短信服务使用的是：" + active);
        smsMessageService.setActive(active);
        smsMessageService.setSmsMessageHistoryService(smsMessageHistoryService);
        SourceTypeEnum storageEnum = SourceTypeEnum.valueOf(active.toUpperCase());
        switch (storageEnum) {
            case TENCENT:
                smsMessageService.setMessage(tencentStorage());
                break;
            case LOCAL:
                smsMessageService.setMessage(localMessage());
                break;
            default:
                throw new RuntimeException("当前存储模式 " + active + " 不支持");
        }
        return smsMessageService;
    }

    @Bean
    @ConditionalOnProperty(value = "sms.active", havingValue = "tencent")
    public SmsTencentMessage tencentStorage() {
        SmsTencentMessage tencentMessage = new SmsTencentMessage();
        MessageProperties.Tencent tencent = this.properties.getTencent();
        tencentMessage.setSecretId(tencent.getSecretId());
        tencentMessage.setSecretKey(tencent.getSecretKey());
        tencentMessage.setRegion(tencent.getRegion());
        tencentMessage.setExpiredTime(tencent.getExpireTime());
        tencentMessage.setSignName(tencent.getSignName());
        tencentMessage.setTemplateId(tencent.getTemplateId());
        tencentMessage.setSmsSdkAppId(tencent.getSdkAppId());
        return tencentMessage;
    }

    @Bean
    @ConditionalOnProperty(value = "sms.active", havingValue = "local")
    public SmsLocalMessage localMessage() {
        SmsLocalMessage localMessage = new SmsLocalMessage();
        MessageProperties.Local local = this.properties.getLocal();
        localMessage.setExpiredTime(local.getExpireTime());
        return localMessage;
    }
}
